<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2016/11/19
 * Time: 16:22
 */

namespace YMApi\Controller;


use Think\Controller;

/**
 * 自提订单
 * Class PickupController
 * @package SDXApi\Controller
 */
class PickupController extends Controller
{

    /**
     * @var \Model|null|\Think\Model
     */
    protected $orderModel = null;

    /**
     * @var \Model|null|\Think\Model
     */
    protected $handleLogModel = null;

    /**
     * @var array
     */
    protected $error = array();

    /**
     * PickupController constructor.
     */
    public function __construct()
    {
        $this->orderModel = D('Orderinfo');
        $this->handleLogModel = D('PickupHandleLog');
    }

    /**
     * Created by Jerry
     */
    public function handle()
    {
        $this->get_pickup_order();
    }

    /**
     * 查找当天22点前下的订单，并在22：30前未确认收货的订单修改配货时间
     * Created by Jerry
     * @return bool
     */
    protected function get_pickup_order()
    {
//        判断当前执行时间
        $handle_time = date('H:i', time());
//        if ($handle_time !== '22:30') {
//            return false;
//        }


        //设置当天22：00时间
        $time = date('Y-m-d', gmtime());
        $formatTime = strtotime($time . ' 22:00');

        $data = $this->orderModel->get_pickup_order_by_time_for_shipping_id($formatTime);

        if (empty($data)) {
            return false;
        }

//        批量修改配送时间
        $result = $this->set_pickup_order_best_time($data);

        if (!$result) {
            return false;
        }

        return true;

    }


    /**
     * 批量修改自提单配送时间
     * Created by Jerry
     * @param $orders
     * @return bool
     */
    protected function set_pickup_order_best_time($orders)
    {
        if (empty($orders)) {
            return false;
        }

        $time = strtotime('+1 days', gmtime());
        $best_time_start = strtotime(date('Y-m-d', $time) . ' 10:00');
        $best_time = strtotime(date('Y-m-d', $time) . ' 22:00');

        $newTimeStart = date('Y-m-d', $time) . ' 10:00';
        $newTimeEnd = date('Y-m-d', $time) . ' 22:00';

        $forend_time = strtotime(date('Y-m-d', $time) . ' 22:00');
        $smsTime['best_time'] = date('Y-m-d', $best_time_start) . ' ' . date('H:i', $best_time_start) . '-' . date('H:i', $forend_time);

        $updateData = array(
            'best_time'         =>  $best_time,
            'best_time_start'   =>  $best_time_start,
        );

        foreach ($orders as $order) {

            $rs = $this->orderModel->update_pickup_order_by_id($order['order_id'], $updateData);

//            统计是否已存在修改过日志
			$number = $this->handleLogModel->get_pickup_handle_log_by_order_id($order['order_id']);

            if (!$rs) {
                $this->insert_log('修改配送时间失败', $order['order_id']);
                continue;
            }

//            日志写入
            $oldTimeStart = date('Y-m-d H:i:s', $order['best_time_start']);
            $oldTimeEnd = date('Y-m-d H:i:s', $order['best_time']);
            $logContent = "修改配送时间成功，修改时间由：{$oldTimeStart} - {$oldTimeEnd} 改为：{$newTimeStart}-{$newTimeEnd}";
            $this->insert_log($logContent, $order['order_id']);
            $this->insert_order_action($order['order_id'], $logContent);

            if ($number > 0) {
//            	发送短信提醒
				$smsResult = $this->send_pickup_order_sms($order['mobile'], $order['consignee'], $order['order_sn'], $order['user_id'], $smsTime, 1);
			}
			else
			{
//            	发送短信提醒
				$smsResult = $this->send_pickup_order_sms($order['mobile'], $order['consignee'], $order['order_sn'], $order['user_id'], $smsTime);
			}

            if(empty($smsResult)){
                $this->insert_log('发送延时配送短信失败', $order['order_id']);
            }

            $this->insert_log('发送延时配送短信成功', $order['order_id']);
        }

        return true;
    }


    /**
     * 插入操作日志
     * Created by Jerry
     * @param $log
     * @return mixed
     */
    protected function insert_log($log, $order_id)
    {
        $logData = array(
            'log'           =>  $log,
            'order_id'      =>  $order_id,
            'created_at'    =>  gmtime(),
        );
        return $this->handleLogModel->insert_pickup_handle_log($logData);
    }

    /**
     * 插入订单操作日志
     * Created by Jerry
     * @param $order_id
     * @return mixed
     */
    protected function insert_order_action($order_id, $content)
    {
        $data = array(
            'order_id'          =>  $order_id,
            'action_user'       =>  '自动脚本',
            'order_status'      =>  OS_CONFIRMED,
            'shipping_status'   =>  SS_SHIPPED,
            'pay_status'        =>  PS_PAYED,
            'action_note'       =>  $content,
            'log_time'          =>  gmtime(),
            'action_type'       =>  4,
        );

        $orderActionModel = D('OrderAction');
        return $orderActionModel->insert_order_action($data);
    }


    /**
     * 发送延时配送短信
     * Created by Jerry
     * @param $mobile
     * @param $userName
     * @param $orderSn
     * @param $userId
     * @param $remark
     * @return mixed
     */
    protected function send_pickup_order_sms($mobile, $userName, $orderSn, $userId, $remark, $type = 0)
    {
    	if ($type == 1) {
			$smsTypeName = 'order_pickup_warning_new';
		}else{
			$smsTypeName = 'order_remind_new';
		}

        return A("Smsapi")->send_message_api($smsTypeName,$mobile, $userName, 0, $orderSn, 0, $userId, $remark, $remark['best_time']);
    }
}